package com.yangjun.service.bussiness;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yangjun.common.DVConstants;
import com.yangjun.dao.mybatis.mapper.businessAnalysis.TaskTraceMapper;
import com.yangjun.entity.businessAnalysis.TaskTraceEntity;
import com.yangjun.entity.common.CompareEntity;
import com.yangjun.utils.DvUtils;
@Service
public class TaskTraceService {
	@Autowired
	protected TaskTraceMapper taskTraceMapper;
	
	protected SimpleDateFormat sdfMonth1 = new SimpleDateFormat("yyyyMM");
	protected SimpleDateFormat sdfMonth2 = new SimpleDateFormat("yyyy-MM");

	public Map<String,Object> queryGeneraleDoneRateRank(String month){
		Map<String,Object> resultMap = Maps.newHashMap();
		List<String> xAxisList = Lists.newArrayList();
		List<Float> valueList = Lists.newArrayList();

		List<TaskTraceEntity> taskTraceEntityList = taskTraceMapper.queryGeneraleDoneRateRank(month);
		if(taskTraceEntityList.size()>0){
			for(TaskTraceEntity taskTraceEntity : taskTraceEntityList){
				String staffName = taskTraceEntity.getStaffName();
				xAxisList.add(staffName);
				Float mixDoneRate = taskTraceEntity.getMixDoneRate()==null?0f:taskTraceEntity.getMixDoneRate();
				valueList.add(mixDoneRate);
			}
		}
		resultMap.put("xAxis", xAxisList);
		resultMap.put("value", valueList);
		return resultMap;
	}
	public List<Object[]>  queryTaskDoneTable(String month){
		List<Object[]> resultList = Lists.newArrayList();
		List<TaskTraceEntity> taskTraceEntityList = taskTraceMapper.queryTaskDoneTable(month);
		if(taskTraceEntityList.size()>0){
			for(TaskTraceEntity taskTraceEntity : taskTraceEntityList){
				String staffName = taskTraceEntity.getStaffName();
				String department= taskTraceEntity.getDepartment();
				int taskAmt= taskTraceEntity.getTaskAmt()==null?0:taskTraceEntity.getTaskAmt();
				float salesAmount = taskTraceEntity.getSalesAmount()==null?0f:taskTraceEntity.getSalesAmount();
				float taskGpRate = taskTraceEntity.getTaskGpRate()==null?0f:taskTraceEntity.getTaskGpRate();
				float doneGpRate = taskTraceEntity.getDoneGpRate()==null?0f:taskTraceEntity.getDoneGpRate();
				int taskGpAmt= taskTraceEntity.getTaskGpAmt()==null?0:taskTraceEntity.getTaskGpAmt();
				float grossProfit = taskTraceEntity.getGrossProfit()==null?0f:taskTraceEntity.getGrossProfit();
				float mixDoneRate = taskTraceEntity.getMixDoneRate()==null?0f:taskTraceEntity.getMixDoneRate();
				Object[] dataArr = new Object[]{staffName,department,taskAmt,salesAmount,taskGpRate,doneGpRate,taskGpAmt,grossProfit,mixDoneRate};
				resultList.add(dataArr);
			}
		}
		DvUtils.PinYinComparatorSortList(resultList);
		return resultList;
	}
	public List<Object[]>  queryDeparmentSalesTable(String month){
		List<Object[]> resultList = Lists.newArrayList();
		List<TaskTraceEntity> taskTraceEntityList = taskTraceMapper.queryDeparmentSalesDetailsTable(month);
		if(taskTraceEntityList.size()>0){
			for(TaskTraceEntity taskTraceEntity : taskTraceEntityList){
				String staffName = taskTraceEntity.getStaffName();
				String department= taskTraceEntity.getDepartment();
				float salesAmount = taskTraceEntity.getSalesAmount()==null?0f:taskTraceEntity.getSalesAmount();
				float grossProfit = taskTraceEntity.getGrossProfit()==null?0f:taskTraceEntity.getGrossProfit();
				float doneGpRate = taskTraceEntity.getDoneGpRate()==null?0f:taskTraceEntity.getDoneGpRate();
				Object[] dataArr = new Object[]{staffName,department,salesAmount,grossProfit,doneGpRate};
				resultList.add(dataArr);
			}
		}
		DvUtils.PinYinComparatorSortList(resultList);
		return resultList;
	}
	
	public Map<String,Object> queryDepartmentSalesLineChartByDay(String staffName,String department,String month){
		String[] queryDateArr = null;
		String[] dateArr = null;
		try {
			Calendar calendar = Calendar.getInstance();
			Date currentDate = sdfMonth1.parse(month);
			calendar.setTime(currentDate);
			calendar.add(Calendar.MONTH, -1);
			String contrastDate = sdfMonth1.format(calendar.getTime());
			queryDateArr = new String[]{month,contrastDate};
			dateArr = new String[]{sdfMonth2.format(sdfMonth1.parse(month)),sdfMonth2.format(sdfMonth1.parse(contrastDate))};
		} catch (ParseException e) {
			e.printStackTrace();
		}
		//一次性查询两个月的数据
		List<TaskTraceEntity> taskTraceEntityList = taskTraceMapper.queryDepartmentSalesLineChartByDay(staffName,department,queryDateArr);
		return queryLineChartData(DVConstants.MONTH_DAY,taskTraceEntityList,dateArr,DVConstants.COMPARISON_LEGEND);
	}	
	private Map<String,Object> queryLineChartData(String[] xAxisArr,
			List<TaskTraceEntity> list,String[] dateArr,String[] nameArr){
		//用来返回结果的结果集
		Map<String,Object> resultMap = Maps.newHashMap();
		//用来存放一天每个小时的数据（或其他时间维度）
		Map<String,TaskTraceEntity> entityMap = null;
		//用来组装每天每个小时的数据（或其他时间维度）
		Map<String,Map<String,TaskTraceEntity>> dateMap = Maps.newHashMap();
		//用来存放返回的对象名
		Map<String,String> nameMap = Maps.newHashMap();
		//构建不同维度的数组
		resultMap.put("xAxis",xAxisArr);

		//遍历集合提取时间作为key，实体作为value,封装不同日期的Map集合
		for(TaskTraceEntity entity : list){
			for(int i=0,len=dateArr.length;i<len;i++){
				//存放返回的对象名
				nameMap.put(dateArr[i], nameArr[i]);
				if(entity.getDataDate().equals(dateArr[i])){
					entityMap = dateMap.get(entity.getDataDate());
					if(entityMap==null){
						entityMap = Maps.newHashMap();
					}
					entityMap.put(entity.getDegreeDate(), entity);
					dateMap.put(entity.getDataDate(), entityMap);
				}
			}
		}
		Map<String,CompareEntity> resultDataMap = Maps.newHashMap();

		//遍历当前日期以及对比日期
		for(Map.Entry<String,Map<String,TaskTraceEntity>> entryDateMap: dateMap.entrySet()){
			
			String date = nameMap.get(entryDateMap.getKey());
			Map<String,TaskTraceEntity> itemMap= entryDateMap.getValue();
			
			String[] salesOrderAmountArr = new String[xAxisArr.length];
			String[] orderCntArr = new String[xAxisArr.length];
			String[] salePctArr = new String[xAxisArr.length];
			String[] doneGpRateArr = new String[xAxisArr.length];
			String[] grossProfitArr = new String[xAxisArr.length];

			//遍历时间数组获取对应的时间实体，空数据给默认值
			for(int i=0,len=xAxisArr.length;i<len;i++ ){
				salesOrderAmountArr[i]=salePctArr[i]=orderCntArr[i]=doneGpRateArr[i]=grossProfitArr[i]="0";
				TaskTraceEntity hourEntity = itemMap.get(xAxisArr[i]);
				if(hourEntity!=null){
					orderCntArr[i]  = hourEntity.getOrderCnt()==null?"0":String.valueOf(hourEntity.getOrderCnt());
					salesOrderAmountArr[i] = hourEntity.getSalePct()==null?"0":hourEntity.getSalesAmount().equals(0f)?"0":String.valueOf(hourEntity.getSalesAmount());
					salePctArr[i] = hourEntity.getSalePct()==null?"0":hourEntity.getSalePct().equals(0f)?"0":String.valueOf(hourEntity.getSalePct());
					doneGpRateArr[i] = hourEntity.getDoneGpRate()==null?"0":hourEntity.getDoneGpRate().equals(0f)?"0":String.valueOf(hourEntity.getDoneGpRate());
					grossProfitArr[i] = hourEntity.getGrossProfit()==null?"0":hourEntity.getGrossProfit().equals(0f)?"0":String.valueOf(hourEntity.getGrossProfit());
				}
			}
			addItemToResultMap(date,"销售额","SalesOrderAmount",salesOrderAmountArr,resultDataMap);
			addItemToResultMap(date,"订单数","orderCnt",orderCntArr,resultDataMap);
			addItemToResultMap(date,"客单价","salePct",salePctArr,resultDataMap);
			addItemToResultMap(date,"毛利率","doneGpRate",doneGpRateArr,resultDataMap);
			addItemToResultMap(date,"毛利额","grossProfit",grossProfitArr,resultDataMap);
		}
		
		resultMap.putAll(resultDataMap);
		resultMap.put("legendName",dateArr);
		return resultMap;
	}
	/**
	 * @Description 组装折线图数据
	 * @param date
	 * @param legendName
	 * @param deminsionName
	 * @param itemArr
	 * @param resultDataMap
	 * @return
	 * @author yangjun
	 * @Date 2017年3月10日 下午2:40:42
	 */
	protected Map<String,CompareEntity> addItemToResultMap(String date,String legendName,String deminsionName,String[] itemArr,Map<String,CompareEntity> resultDataMap){
		CompareEntity compareEntity = resultDataMap.get(deminsionName);
		if(compareEntity==null){
			compareEntity = new CompareEntity();
			compareEntity.setName(legendName);
		}
		if("currentData".equals(date)){
			compareEntity.setCurrentDataArr(itemArr);
		}else if("contrastData".equals(date)){
			compareEntity.setContrastDataArr(itemArr);
		}
		resultDataMap.put(deminsionName, compareEntity);
		if(resultDataMap.get(deminsionName).getContrastDataArr()==null){
			resultDataMap.get(deminsionName).setContrastDataArr(new String[]{});
		}
		if(resultDataMap.get(deminsionName).getCurrentDataArr()==null){
			resultDataMap.get(deminsionName).setCurrentDataArr(new String[]{});
		}
		return resultDataMap;
	}
}
